<script setup lang="tsx">
import {
  getAgentWithdrawalAmtApi,
  agentWithdrawalBillPageApi,
  agentWithdrawalBillAuditApi
} from '@/api/financial'
import type { MerchantListParams } from '@/api/BusinessManagement/types'
import { ElButton, ElMessageBox } from 'element-plus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import { AgentWithdrawalBillDict } from '@/utils/dict'
import { hasPermission as hasPermis } from '@/components/Permission/src/utils'

const { t } = useI18n()

const activeTab = ref(0)

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await agentWithdrawalBillPageApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      state: unref(activeTab) === 0 ? '' : unref(activeTab),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const tabs = [
  {
    label: '全部',
    value: 0
  },
  {
    label: '待审核',
    value: 1
  },
  {
    label: '提现中',
    value: 4
  },
  {
    label: '审核成功',
    value: 3
  },
  {
    label: '提现成功',
    value: 5
  },
  {
    label: '审核失败',
    value: 2
  },
  {
    label: '提现失败',
    value: 6
  }
]

const searchRef = ref()

const tabChange = (v) => {
  searchRef.value[0].reset()
  activeTab.value = v
  currentPage.value = 1
  searchParams.value = {}
  getList()
  getWithdrawalAmt({
    state: unref(activeTab) === 0 ? '' : unref(activeTab)
  })
}

const withdrawalAmt = ref<any>({})
const getWithdrawalAmt = async (data) => {
  if (!hasPermis('GET /agentWithdrawalBill/getWithdrawalAmt')) {
    return false
  }
  const res = await getAgentWithdrawalAmtApi(data)
  withdrawalAmt.value = res.data
  console.log(withdrawalAmt.value)
}

getWithdrawalAmt({})

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: 'ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'applyNo',
    label: '申请编号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 220
    }
  },
  {
    field: 'nickName',
    label: '经纪人名称',
    search: {
      componentProps: {
        placeholder: '请输入经纪人名称'
      }
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'nickName',
    label: '申请人',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'tradeAmt',
    label: '提现金额',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'cardNo',
    label: '提现账号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 220,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div class={'flex items-center'}>{row.cardName}</div>
              <div class={'flex items-center'}>{row.bankName}</div>
              <div class={'flex items-center'}>{row.cardNo}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'state',
    label: '状态',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.state && AgentWithdrawalBillDict[row.state]}</div>
              {(row.state === 2 || row.state === 6) && (
                <div style="color: #F59A23;">
                  原因：{row.refuseReason ? row.refuseReason : '无'}
                </div>
              )}
            </>
          )
        }
      }
    }
  },
  {
    field: 'applyTime',
    label: '申请时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 220
    }
  },
  {
    field: 'auditTime',
    label: '审核时间',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 220
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 200,
      slots: {
        default: (data: any) => {
          const row = data.row as MerchantListParams
          if (row.state === 1) {
            return (
              <>
                <ElButton
                  v-hasPermi="POST /agentWithdrawalBill/audit"
                  type="primary"
                  link
                  onClick={() => hanleAudit(row, 3)}
                >
                  审核通过
                </ElButton>
                <ElButton
                  v-hasPermi="POST /agentWithdrawalBill/audit"
                  type="primary"
                  link
                  onClick={() => hanleAudit(row, 2)}
                >
                  审核不通过
                </ElButton>
              </>
            )
          }
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { applyTime, ...rest } = params
  let applyTimeStart, applyTimeEnd
  if (applyTime && applyTime.length > 0) {
    applyTimeStart = applyTime[0]
    applyTimeEnd = applyTime[1]
  }
  currentPage.value = 1
  searchParams.value = {
    applyTimeStart,
    applyTimeEnd,
    ...rest
  }
  getList()
  getWithdrawalAmt({ state: unref(activeTab) === 0 ? '' : unref(activeTab), ...searchParams.value })
}

const hanleAudit = async (row: any, i) => {
  console.log(row)
  if (i === 3) {
    ElMessageBox.confirm('确认审核通过该笔提现？')
      .then(async () => {
        console.log('确定')
        const setData = {
          id: row.id,
          auditState: i
        }
        const res = await agentWithdrawalBillAuditApi(setData)
        console.log(res)
        currentPage.value = 1
        getList()
        getWithdrawalAmt({
          state: unref(activeTab) === 0 ? '' : unref(activeTab),
          ...searchParams.value
        })
      })
      .catch(() => {
        // catch error
        console.log('取消')
      })
  } else {
    ElMessageBox.prompt('确认审核拒绝该笔提现？', {
      // inputErrorMessage: '请填写拒绝理由'
      inputValidator: (val) => {
        if (val === null || val.length < 1 || val.length > 50) {
          return false
        }
        return true
      },
      inputErrorMessage: '此项不能为空，最多可输入50个字符'
    })
      .then(async ({ value }) => {
        console.log(`确定:${value}`)
        const setData = {
          id: row.id,
          auditState: i,
          refuseReason: value
        }
        const res = await agentWithdrawalBillAuditApi(setData)
        console.log(res)
        currentPage.value = 1
        getList()
        getWithdrawalAmt({
          state: unref(activeTab) === 0 ? '' : unref(activeTab),
          ...searchParams.value
        })
      })
      .catch(() => {
        console.log('取消')
      })
  }
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px">
      <ElTabs v-model="activeTab" @tab-change="tabChange">
        <div
          v-hasPermi="'GET /agentWithdrawalBill/getWithdrawalAmt'"
          style="background: rgb(24 144 255 / 16.9%)"
          class="flex p-10px mb-4 text-14px font-bold"
        >
          <div class="mr-20">累计申请金额：￥{{ withdrawalAmt.totalApplyAmt }}</div>
          <div>累计已提现金额：￥{{ withdrawalAmt.totalSuccessAmt }}</div>
        </div>
        <ElTabPane v-for="item in tabs" :key="item.value" :label="item.label" :name="item.value">
          <Search
            ref="searchRef"
            :schema="allSchemas.searchSchema"
            @reset="setSearchParams"
            @search="setSearchParams"
          />
          <Table
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :columns="allSchemas.tableColumns"
            :data="dataList"
            :loading="loading"
            @register="tableRegister"
            :pagination="{
              total
            }"
          />
        </ElTabPane>
      </ElTabs>
    </ContentWrap>
  </div>
</template>
